/**
 * @author VernHe
 * @date 2021年05月15日 13:44
 */
public class Solution_075 {
    public static void main(String[] args) {
//        int[] nums = new int[]{2, 0, 2, 1, 1, 0};
        int[] nums = new int[]{0,0};
        new Solution_075().sortColors(nums);

    }

    public void sortColors(int[] nums) {
        // 参数判断
        if (nums == null || nums.length < 2) {
            return;
        }

        // 定义两个指针，并初始化
        int left = 0;
        while (left < nums.length && nums[left] == 0) {
            left++;
        }
        int right = nums.length - 1;
        while (right >= 0 && nums[right] == 2) {
            right--;
        }
        if (right <= left) {
            return;
        }
        System.out.println("排序开始！left,right分别为：" + left + " " + right);
        // 排序
        int cur = left;
        while (left < right && cur <= right) {
            if (nums[cur] == 1) {
                cur++;
                System.out.println("遇到1，cur++，此时数组的left: " + left + " right: " + right + " cur: " + cur);
                pringNums(nums);
                continue;
            }
            if (nums[cur] == 2) {
                swap(nums, cur, right);
                right--;
                System.out.println("遇到2，right--，此时数组的left: " + left + " right: " + right + " cur: " + cur);
                pringNums(nums);
                continue;
            }
            if (nums[cur] == 0) {
                swap(nums, cur, left);
                left++;
                cur++;
                System.out.println("遇到0，left++，此时数组的left: " + left + " right: " + right + " cur: " + cur);
                pringNums(nums);
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        if (i == j) {
            return;
        }
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    private void pringNums(int[] nums) {
        for (int num : nums) {
            System.out.printf(num + " ");
        }
        System.out.println();
    }
}

